package k8s

import (
	"fmt"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"encoding/json"
)

type ClusterRole struct {
	Name string						`json:"name"`

	Kind string						`json:"kind"`
	//Rules []permission				`json:"rules"`
	Rules []map[string][]string				`json:"rules"`
	//Trees [][]ElTreeRoot					`json:"trees"`
	FinallyTrees []FinallyTree				`json:"finallytrees"`

	CreateDate string				`json:"createdate"`
}

//type permission struct {
//	ApiGroups []string				`json:"apiGroups"`
//	Resources []string				`json:"resources"`
//	NonResourceURLs []string		`json:"nonResourceURLs"`
//	Verbs []string					`json:"verbs"`
//}

func GetClusterRole() (roles []ClusterRole,err error) {
	clusterroles,_ := clientset.RbacV1().ClusterRoles().List(metav1.ListOptions{})
	for _,role := range  clusterroles.Items{
		var r ClusterRole
		r.Name = role.Name
		r.CreateDate = role.CreationTimestamp.Format("2006-01-02")
		//fmt.Println(role.Name)
		//fmt.Println(role.CreationTimestamp.Format("2006-01-02"))
		fmt.Println(role.ObjectMeta.Annotations["kubectl.kubernetes.io/last-applied-configuration"])
		//fmt.Println(reflect.TypeOf(role.ObjectMeta))
		//fmt.Printf("%+v\n",role.ObjectMeta.Annotations)
		//fmt.Printf("%+v\n",role.ObjectMeta.Annotations)
		//for kk,vv := range role.ObjectMeta.Annotations {
		//	fmt.Println("kk " , kk , " and Vv , " ,vv)
		//}

		if err = json.Unmarshal([]byte(role.ObjectMeta.Annotations["kubectl.kubernetes.io/last-applied-configuration"]),&r) ; err != nil {
			fmt.Println("role string to json error",err.Error())
		} else {
			fmt.Printf("%+v\n",r)
			//r.Trees = append(r.Trees,convertToTree(r.Rules))
			r.FinallyTrees = convertToTree(r.Rules)
		}
		//trees = append(trees,convertToTree(r.Rules))

		roles = append(roles,r)

	}



	return
}

//adapt to element-ui tree

type ElTreeRoot struct {
	Label string					`json:"label"`
	Children []ElTreeLeaf			`json:"children"`
}

type ElTreeLeaf struct {
	Label string					`json:"label"`
}

type FinallyTree struct {
	Label string 					`json:"label"`
	Children []ElTreeRoot    		`json:"children"`
}


func convertToTree(rules []map[string][]string) (finallyTree []FinallyTree )  {
	fmt.Println("debug convert")
	fmt.Println(rules)
	var eltrees [][]ElTreeRoot
	for _,rule := range rules {
		var tmptree []ElTreeRoot
		for k,v := range rule {
			var tree ElTreeRoot

			tree.Label = k
			for _, leaf := range v {
				l := ElTreeLeaf{
					Label: leaf,
				}
				tree.Children = append(tree.Children,l)
			}

			tmptree = append(tmptree,tree)

		}
		eltrees = append(eltrees,tmptree)

	}

	finallyTree = encapsulationTree(eltrees)

	return
}

func encapsulationTree(eltrees [][]ElTreeRoot) (finallyTress []FinallyTree) {
	//var finallyTress []FinallyTree
	for i,trees := range eltrees {
		var tree FinallyTree
		tree.Label = fmt.Sprintf("rule-%d",i)
		tree.Children = trees
		finallyTress = append(finallyTress,tree)
	}
	//fmt.Println("the finaly trees " , finallyTress)
	return
}